import logging
import threading

from flask import session, jsonify, request
from flask_restful import Resource

from utils.login_helper import check_user_state
from utils.sql_user import get_icode, get_user_list, gen_icode

lock = threading.Lock()

class get_active_code(Resource):

    @check_user_state
    def post(self):
        """
        获取icode列表
        :return: list
        :example: ['093a3Xag0bHLfz8q', 'xKfn9oClWHALRz3P', 'Sz2XbkrSEiO3dBcu']
        """
        level = session.get('level')

        if level != 0:
            return '0'

        with lock:
            data = get_icode()

        logging.info(f"用户({session['email']})请求邀请码列表")

        return jsonify(data)

class get_user_list_api(Resource):

    @check_user_state
    def post(self):
        """
        获取用户列表
        :return: list
        :returns: '0':权限不足,'-1':非法参数,'-2':范围过大
        :example:[{'uid': 1, 'email': 'kawaiiorv@gmail.com', 'name': '枝江最甜小草莓', 'password': '******'}]
        """
        level = session['level']

        if level != 0 and level != 1:
            return '0'

        form = request.form
        index = form.get("index")
        end = form.get("end")

        try:
            index = int(index)
            end = int(end)
        except ValueError:
            return '-1'

        if (index - end) ** 2 > 10000:
            return '-2'

        with lock:
            data = get_user_list(access=level)

        logging.info(f"用户({session['email']})请求用户列表")

        return jsonify(data)

class add_icode_api(Resource):

    @check_user_state
    def post(self):
        """
        生成icode
        :return: 0:权限不足,1:成功 ,-1:失败
        """
        level = session.get('level')

        if level != 0:
            return '0'

        try:
            gen_icode(5)
        except Exception as e:
            print(e)
            return '-1'

        logging.info(f"用户({session['email']})请求生成邀请码")

        return '1'
